//
//  SaliorQiuzhiViewController.m
//  shuiyun
//
//  Created by 徐双 on 2017/9/6.
//  Copyright © 2017年 qianyi. All rights reserved.
//

#import "SaliorQiuzhiViewController.h"
#import "ReleaseRecodeViewCell.h"
#import "SaliorQiuzhiTableViewCell.h"
#import "ReleaseTextViewTableViewCell.h"
#import "STPhotoKitController.h"
#import "UIImagePickerController+ST.h"
#import "UIButton+AddAction.h"
#import "ICN_HeadImageSelView.h"



@interface SaliorQiuzhiViewController ()<UITableViewDelegate,UITableViewDataSource,UIImagePickerControllerDelegate,STPhotoKitDelegate,UINavigationControllerDelegate>

{
    NSString * q_xinnin;
    NSString * q_zhiwu;
    NSString * q_tel;
    NSString * q_conter;
    NSString * q_jingyan;
    NSString * username;
    NSString * q_nianling;
    NSString * q_xinzi;
    NSString * title;
    
    NSString * titlepic;
    
    
    UIView *grayView;

}

//@property(nonatomic,strong)UIImage * headImage;

@property (nonatomic, strong) UITableView *tableView;

@property (nonatomic, strong) UIImage *image;
@property (nonatomic, strong) NSData *imageData;

@property (nonatomic, strong) ICN_HeadImageSelView *changeHeadImageView;

@property(nonatomic,strong)SaliorQiuzhiTableViewCell * cellImage;
@end

@implementation SaliorQiuzhiViewController

- (void)viewWillAppear:(BOOL)animated{
    
    
    [super viewWillAppear:animated];
    [self.navigationController setNavigationBarHidden:NO animated:NO];
    
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [self creationView];
    [self regeditCell];
    
    // Do any additional setup after loading the view.
}
- (void)creationView {
    [super viewDidLoad];
    
   // [self setTitle:@"发布档案"];
    
    
    
    //初始化tableView
    
    self.tableView = [[UITableView alloc] init];
    self.tableView.frame = CGRectMake(0, 0, DEF_SCREEN_WIDTH, DEF_SCREEN_HEIGHT - 64);
    
    
    self.tableView.tableFooterView = [[UITableView alloc] initWithFrame:CGRectZero];
    
    self.tableView.backgroundColor = [UIColor whiteColor];
    
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    // self.tableView.estimatedRowHeight = 400;
    self.tableView.separatorStyle = UITableViewCellAccessoryNone;//去掉分割线
    
    
    [self.view addSubview:self.tableView];
    self.view.backgroundColor = [UIColor colorWithRed:245 / 255.0f green:245 / 255.0f blue:245 / 255.0f alpha:1];
    
    UIButton *buttonOut = [[UIButton alloc] init];
    [self.view addSubview:buttonOut];
    [buttonOut mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.view).offset(16);
        make.right.equalTo(self.view).offset(-16);
        make.bottom.equalTo(self.view).offset(-9);
        make.height.offset(40);
        
    }];
    [buttonOut setTitle:@"发布" forState:UIControlStateNormal];
    buttonOut.backgroundColor = getColor(@"3F87F6");
    [buttonOut setTitleColor:getColor(@"FFFFFF") forState:UIControlStateNormal];
    [buttonOut addTarget:self action:@selector(publicLick) forControlEvents:UIControlEventTouchUpInside];
    
}

-(void)publicLick{
    
    NSMutableDictionary *productParams=[[NSMutableDictionary alloc]init];
    NSString *token = [PublicFunction getConfigWithKey:@"token"];
    [productParams setValue:token forKey:@"token"];
    NSString * userid = [PublicFunction getConfigWithKey:@"userid"];
    [productParams setValue:userid forKey:@"userid"];
    [productParams setValue:title forKey:@"title"];
    [productParams setValue:q_xinzi forKey:@"defendant"];
    [productParams setValue:q_zhiwu forKey:@"d_phone"];
    [productParams setValue:q_tel forKey:@"plaintiff"];
    [productParams setValue:q_conter forKey:@"p_phone"];
    [productParams setValue:q_jingyan forKey:@"d_company"];
    [productParams setValue:username forKey:@"defendant"];
    [productParams setValue:q_nianling forKey:@"d_phone"];
    [productParams setValue:q_xinzi forKey:@"plaintiff"];
    
        
    /*方式一：使用NSData数据流传图片*/
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json",
                                                         @"text/plain",
                                                         @"text/javascript",
                                                         @"text/json",
                                                         @"text/html",
                                                         @"image/jpeg", nil];
    [manager POST:ReleaseQiuzhi parameters:productParams constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
        
        
        if (self.image) {
            
            self.imageData = UIImageJPEGRepresentation(self.image,0.005);
        }else {
            
            self.imageData = UIImageJPEGRepresentation([UIImage imageNamed:@"添加头像"],0.005);
            
        }
        
        
        //压缩图片
        
        //拼接图片名称+时间确保不重复命名
        NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
        formatter.dateFormat = @"yyyyMMddHHmmss";
        NSString *imageFileName = [NSString stringWithFormat:@"%@.jpg", [formatter stringFromDate:[NSDate date]]];
        // 测试输出文件名
        
        //上传图片，以文件流的格式sdf
        
        //        [formData appendPartWithFileData:UIImageJPEGRepresentation([UIImage imageNamed:@"1"], 5.0) name:@"image1" fileName:@"1.jpg" mimeType:@"image/jpeg"];
        
        [formData appendPartWithFileData:_imageData name:@"titlepic" fileName:imageFileName mimeType:@"image/JPG"];
        
    } success:^(AFHTTPRequestOperation *operation, id responseObject) {
        
        NSString *strtmp = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
        NSString *requestTmp = [NSString stringWithString: strtmp];
        NSData *resData = [[NSData alloc] initWithData:[requestTmp dataUsingEncoding:NSUTF8StringEncoding]];
        NSDictionary *resultDic = [NSJSONSerialization JSONObjectWithData:resData options:NSJSONReadingMutableLeaves error:nil];  //解析
        NSLog(@"+++>%@", resultDic);
        NSLog(@"--->%@", resultDic[@"msg"]);
        
        
        if ([[resultDic objectForKey:@"code"]intValue]==1) {
            
            
            //NSLog(@"!!!!!!!!!!!!!!!%@",_dataArr);
            
            [PublicFunction showAlert:nil message:@"发布成功" duration:10.0f];
            
            [self.tableView reloadData];
            
            [self.navigationController popViewControllerAnimated:YES];
        }
        
        else {
            
            [PublicFunction showAlert:nil message:[resultDic objectForKey:@"msg"] duration:5.0f];
            
        }

        
        
        
        
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        
        NSLog(@"%@",error);
        
        [PublicFunction showAlert:nil message:@"没有连接网络" duration:10.0f];
    }];
    

}


-(void)regeditCell{
    
    [self.tableView registerNib:[UINib nibWithNibName:@"ReleaseRecodeViewCell" bundle:nil] forCellReuseIdentifier:@"ReleaseRecodeViewCell"];
    
    
    [self.tableView registerNib:[UINib nibWithNibName:@"SaliorQiuzhiTableViewCell" bundle:nil] forCellReuseIdentifier:@"SaliorQiuzhiTableViewCell"];
    
    [self.tableView registerNib:[UINib nibWithNibName:@"ReleaseTextViewTableViewCell" bundle:nil] forCellReuseIdentifier:@"ReleaseTextViewTableViewCell"];
}

#pragma mark - ---------- Cell的数量 ----------
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 10;
    
    
}

#pragma mark - ---------- 每个Cell的高度 ----------
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.row == 0) {
        
        return 100;
    }else if(indexPath.row == 9){
    
        return 200;
    
    }
    
    return 50;
    
}

#pragma mark - ---------- 每个Cell的内容 ----------
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
   ReleaseRecodeViewCell * cell = [tableView dequeueReusableCellWithIdentifier:@"ReleaseRecodeViewCell"];
    
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    
    if (indexPath.row == 0) {
        
       
        _cellImage = [tableView dequeueReusableCellWithIdentifier:@"SaliorQiuzhiTableViewCell"];
        _cellImage.selectionStyle = UITableViewCellEditingStyleNone;
        
        
        
        
        
        return _cellImage;
        
    }else if (indexPath.row == 1){
        
        cell.nameLabel.text = @"联系人:";
        cell.textView.placeholder = @"请输入联系人";
        cell.textView.text = q_xinnin;
    }else if (indexPath.row == 2){
        
        cell.nameLabel.text = @"职位:";
        cell.textView.placeholder = @"请输入职位";
        cell.textView.text = q_zhiwu;
    }else if (indexPath.row == 3){
        
        cell.nameLabel.text = @"电话:";
        cell.textView.placeholder = @"请输入电话";
        cell.textView.text = q_tel;
    }else if (indexPath.row == 4){
        
        cell.nameLabel.text = @"工作经验:";
        cell.textView.placeholder = @"请输入工作经验";
        cell.textView.text = q_jingyan;
        
    }else if (indexPath.row == 5){
        
        cell.nameLabel.text = @"用户名:";
        cell.textView.placeholder = @"请输入用户名";
        cell.textView.text = username;
    }else if (indexPath.row == 6){
        
        cell.nameLabel.text = @"年龄:";
        cell.textView.placeholder = @"请输入年龄";
        cell.textView.text = q_nianling;
    }else if (indexPath.row == 7){
        
        cell.nameLabel.text = @"薪资:";
        cell.textView.placeholder = @"请输入薪资";
        cell.textView.text = q_xinzi;
   
    }else if (indexPath.row == 8){
        
        cell.nameLabel.text = @"标题:";
        cell.textView.placeholder = @"请输入标题";
        cell.textView.text = title;
    }else{
    
        ReleaseTextViewTableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:@"ReleaseTextViewTableViewCell"];
        
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        cell.contentLabel.text = @"备注:";
        cell.contentTextView.text = q_conter;
        
        return cell;
    }
    return cell;
    
}
#pragma mark - ---------- 每个Cell的点击事件 ----------
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.row == 0) {
        
        grayView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, DEF_SCREEN_WIDTH, DEF_SCREEN_HEIGHT)];
        grayView.backgroundColor = [UIColor colorWithRed:0 / 255.0f green:0 / 255.0f blue:0 / 255.0f alpha:0.2];
        
        [[UIApplication sharedApplication].keyWindow addSubview:grayView];
        
        UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(dismissContactView)];
        [grayView addGestureRecognizer:tapGesture];
        
        [grayView addSubview:self.changeHeadImageView];
        [self.changeHeadImageView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.bottom.mas_equalTo(self.view);
            make.size.mas_equalTo(CGSizeMake(DEF_SCREEN_WIDTH, 160));
        }];
        
        self.changeHeadImageView.layer.cornerRadius = 8;
        [self.changeHeadImageView.takePhotoButton addAction:^(NSInteger tag) {
            UIImagePickerController *controller = [UIImagePickerController imagePickerControllerWithSourceType:UIImagePickerControllerSourceTypeCamera];
            [grayView removeFromSuperview];
            if ([controller isAvailableCamera] && [controller isSupportTakingPhotos]) {
                [controller setDelegate:self];
                [self presentViewController:controller animated:YES completion:nil];
            }else {
                NSLog(@"%s %@", __FUNCTION__, @"相机权限受限");
            }
        }];
        [self.changeHeadImageView.localAlbumButton addAction:^(NSInteger tag) {
            UIImagePickerController *controller = [UIImagePickerController imagePickerControllerWithSourceType:UIImagePickerControllerSourceTypePhotoLibrary];
            [controller setDelegate:self];
            [grayView removeFromSuperview];
            if ([controller isAvailablePhotoLibrary]) {
                [self presentViewController:controller animated:YES completion:nil];
            }
        }];
        [self.changeHeadImageView.closeViewButton addAction:^(NSInteger tag) {
            [self dismissContactView];
        }];
  
    }
    
}

#pragma mark ----------------------- 相册／相机 ---------------------

- (void)photoKitController:(STPhotoKitController *)photoKitController resultImage:(UIImage *)resultImage
{
    // [self.imageButton setImage:resultImage forState:UIControlStateNormal];
    
    
    self.image = resultImage;
    _cellImage.iconImageView.image = resultImage;
    
    //    self.shoppicImage.image = resultImage;
//self.headImage.image = resultImage;
    //[_headImg setImage:resultImage forState:UIControlStateNormal];
    
}

#pragma mark - 2.UIImagePickerController的委托

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info
{
    [picker dismissViewControllerAnimated:YES completion:^{
        UIImage *imageOriginal = [info objectForKey:UIImagePickerControllerOriginalImage];
        STPhotoKitController *photoVC = [STPhotoKitController new];
        [photoVC setDelegate:self];
        [photoVC setImageOriginal:imageOriginal];
        
        [photoVC setSizeClip:CGSizeMake(100 ,100)];
        
        
        [self presentViewController:photoVC animated:YES completion:nil];
    }];
}

- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker {
    [picker dismissViewControllerAnimated:YES completion:^(){
    }];
}
- (void)dismissContactView {
    [grayView removeFromSuperview];
}

#pragma mark - ---------- 懒加载 ----------
- (ICN_HeadImageSelView *)changeHeadImageView {
    if (!_changeHeadImageView)
    {
        _changeHeadImageView = [[NSBundle mainBundle] loadNibNamed:@"ICN_HeadImageSelView" owner:self options:nil].lastObject;
    }
    return _changeHeadImageView;
}


@end
